package com.bdqn.t330.ch11.controller;

import com.bdqn.t330.ch11.entity.Page;
import com.bdqn.t330.ch11.entity.SysUser;
import com.bdqn.t330.ch11.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {


    private Logger logger = Logger.getLogger(UserController.class);

    @Autowired
    UserService userService;

    //public String add();
    //public String delete();
    //public String update();

    @RequestMapping("/userList")
    public String userList(Model model) {
        List<SysUser> userList = userService.getUserList();
        model.addAttribute("list", userList);
        return "/user/list";
    }

    @RequestMapping("/userListPage")
    public String userListPage(Model model, Integer pageIndex, Integer pageSize, String userName) {

        if (pageIndex == null) {
            pageIndex = 1;
        }
        if (pageSize == null) {
            pageSize = 5;
        }

        Page page = new Page();
        page.setCurrentPage(pageIndex);
        page.setPageSize(pageSize);

        List<SysUser> listPage = userService.getUserListPageBiz(pageIndex, pageSize, userName);
        page.setList(listPage);
        //设置总记录数的同时要计算出总页数
        page.setTotalRecord(userService.getUserListPageCount(userName));

        //model.addAttribute("listPage", listPage);
        //回传当前页码
        //model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("page", page);
        model.addAttribute("userName", userName);
        return "/user/listPage";
    }

    @RequestMapping("/toAdd")
    public String getUserList() {
        return "/user/add";
    }

    @RequestMapping("/add")
    public String add(Model model, SysUser sysUser, HttpSession session) {
        if (session.getAttribute("sysUser") == null) {
            throw new RuntimeException("请先登录!");
        }
        SysUser user = (SysUser) session.getAttribute("sysUser");
        sysUser.setCreatedBy(user.getId());
        sysUser.setCreationDate(new Date());
        int count = userService.add(sysUser);
        if (count > 0) {
            return "redirect:/user/userListPage";
        } else {
            return "/user/add";
        }
    }

    @RequestMapping("/deleteById")
    public String getUserList(Integer id) {
        int count = userService.deleteByIdBiz(id);
        if (count > 0) {
            return "redirect:/user/userListPage";
        } else {
            return "/user/add";
        }
    }
}
